package cn.itcast.controller.cargo;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.company.Company;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ContractProductVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contract")
public class ContractController extends BaseController {

    @Reference
    private ContractService contractService;

    @RequestMapping(value = "/list",name = "展示购销合同列表数据")
    public String findAll(@RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer pageSize){

//        查询购销合同 应该有什么条件  companyId   按照生成时间排序 降序
        ContractExample example = new ContractExample();
        ContractExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getCompanyId());
        example.setOrderByClause("create_time desc");

        User user = getUser();
//        1-企业管理员                 条件只有 companyId
//        2-管理所有下属部门和人员     条件有 companyId + createDept like '100%'
//        3-管理本部门                  条件有 companyId + createDept = '100'
//        4-普通员工                   条件有 companyId + createBy = 'id'
        Integer degree = user.getDegree();
        if(degree==4){
            criteria.andCreateByEqualTo(user.getId());
        }else if(degree==3){
            criteria.andCreateDeptEqualTo(user.getDeptId());
        }else if(degree==2){
            criteria.andCreateDeptLike(user.getDeptId()+"%");
        }
        PageInfo<Contract> pageInfo = contractService.findAll(example,page,pageSize);
        request.setAttribute("page",pageInfo); //这个 “page” 不能写错，因为页面就是取的是page中的值
        return "cargo/contract/contract-list";
    }


    @RequestMapping(value = "/toAdd",name = "进入到添加购销合同页面")
    public String toAdd(){
        return "cargo/contract/contract-add";
    }

    @RequestMapping(value = "/edit",name = "保存购销合同方法")
    public String edit(Contract contract){
        if(StringUtils.isEmpty(contract.getId())){
            contract.setId(UUID.randomUUID().toString());
            contract.setCompanyId(getCompanyId());
            contract.setCompanyName(getCompanyName());
            contract.setCreateTime(new Date());
            contract.setState(0);

            contract.setCreateBy(getUser().getId());      //在细颗粒度控制时用到
            contract.setCreateDept(getUser().getDeptId());//在细颗粒度控制时用到

            contractService.save(contract);
        }else{
            contractService.update(contract);
        }
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/toUpdate",name = "进入到修改购销合同页面")
    public String toUpdate(String id){
        Contract contract = contractService.findById(id);
        request.setAttribute("contract",contract);

        return "cargo/contract/contract-add";
    }

    @RequestMapping(value = "/print",name = "进入到导出出货表页面")
    public String print(){

        return "cargo/print/contract-print";
    }


    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    @Autowired
    private DownloadUtil downloadUtil;

    @RequestMapping(value = "/printExcel",name = "导出出货表数据")
    public void printExcel(String inputDate) throws Exception{

//        根据船期查询数据
        List<ContractProductVo> contractProductVoList = contractService.findContractProductVoByShipTime(inputDate);
//        把数据放入到excel中
//        1、创建一个工作薄 里面什么都没有
        Workbook workbook = new XSSFWorkbook();

//        2、创建一个工作表 里面什么都没有
        Sheet sheet = workbook.createSheet("测试");

//        调整列宽
        sheet.setColumnWidth(1,26*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(2,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(3,26*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(4,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(5,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(6,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(7,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(8,16*256); //1代表一个字母宽度的256分之一

//        创建第一行的8个单元格
        Row row = sheet.createRow(0);
        row.setHeightInPoints(36);
        Cell cell = null;
        for (int i = 1; i <= 8; i++) {
            cell = row.createCell(i);
            cell.setCellStyle(bigTitle(workbook));
        }
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
//        2020-06---->2020年6月份出货表     2019-12--->2019年12月份出货表
        sheet.getRow(0).getCell(1).
                setCellValue(inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表");
//        第二行都是小标题
//        客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
        String title[] = new String[]{"客户","合同号","货号","数量","工厂","工厂交期","船期","贸易条款"};
        row = sheet.createRow(1);
        row.setHeightInPoints(26);
        for (int i = 1; i <= 8; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i-1]);
            cell.setCellStyle(title(workbook));
        }

//        导出具体的内容
        int rowIndex=2;
        for (ContractProductVo contractProductVo : contractProductVoList) {
            row = sheet.createRow(rowIndex);
//            客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
            row.setHeightInPoints(36);

            cell = row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName()); //客户
            cell.setCellStyle(text(workbook));

            cell = row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo()); //合同号
            cell.setCellStyle(text(workbook));

            cell = row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo()); //货号
            cell.setCellStyle(text(workbook));

            cell = row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());//数量
            cell.setCellStyle(text(workbook));

            cell = row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());//工厂
            cell.setCellStyle(text(workbook));

            cell = row.createCell(6);
            cell.setCellValue(sdf.format(contractProductVo.getDeliveryPeriod()));//工厂交期
            cell.setCellStyle(text(workbook));

            cell = row.createCell(7);
            cell.setCellValue(sdf.format(contractProductVo.getShipTime()));//船期
            cell.setCellStyle(text(workbook));

            cell = row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());//贸易条款
            cell.setCellStyle(text(workbook));

            rowIndex++;
        }
//        文件导出 文件下载 一个流：文件的输出流  两个头：文件的打开方式、文件的mime类型
//        ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream); //把workbook中的内容写入到缓存流中
        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");

    }


    @RequestMapping(value = "/printExcelWithTemplate",name = "使用模板导出出货表数据")
    public void printExcelWithTempate(String inputDate) throws Exception{

//        根据船期查询数据
        List<ContractProductVo> contractProductVoList = contractService.findContractProductVoByShipTime(inputDate);
//        把数据放入到excel中
//        1、创建一个有内容的工作薄
        String templatePath = session.getServletContext().getRealPath("/make/xlsprint/tOUTPRODUCT.xlsx");
        Workbook workbook = new XSSFWorkbook(new FileInputStream(templatePath));

//        2、获取一个工作表
        Sheet sheet = workbook.getSheetAt(0);

        sheet.getRow(0).getCell(1).
                setCellValue(inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表");
//        获取样式
        Row row = null;
        row =sheet.getRow(2);

        CellStyle[] cellStyles = new CellStyle[8];
        for (int i = 1; i <= 8; i++) {
            cellStyles[i-1] = row.getCell(i).getCellStyle();
        }
        
        
        
//        导出具体的内容
        int rowIndex=2;
        
        Cell cell = null;
        for (ContractProductVo contractProductVo : contractProductVoList) {
            row = sheet.createRow(rowIndex);
//            客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
            row.setHeightInPoints(36);

            cell = row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName()); //客户
            cell.setCellStyle(cellStyles[0]);

            cell = row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo()); //合同号
            cell.setCellStyle(cellStyles[1]);

            cell = row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo()); //货号
            cell.setCellStyle(cellStyles[2]);

            cell = row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());//数量
            cell.setCellStyle(cellStyles[3]);

            cell = row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());//工厂
            cell.setCellStyle(cellStyles[4]);

            cell = row.createCell(6);
            cell.setCellValue(sdf.format(contractProductVo.getDeliveryPeriod()));//工厂交期
            cell.setCellStyle(cellStyles[5]);

            cell = row.createCell(7);
            cell.setCellValue(sdf.format(contractProductVo.getShipTime()));//船期
            cell.setCellStyle(cellStyles[6]);

            cell = row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());//贸易条款
            cell.setCellStyle(cellStyles[7]);

            rowIndex++;
        }

        workbook.removeSheetAt(1);
//        文件导出 文件下载 一个流：文件的输出流  两个头：文件的打开方式、文件的mime类型
//        ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream); //把workbook中的内容写入到缓存流中
        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");

    }



    @RequestMapping(value = "/printExcelMillion",name = "导出百万数据")
    public void printExcelMillion(String inputDate) throws Exception{

//        根据船期查询数据
        List<ContractProductVo> contractProductVoList = contractService.findContractProductVoByShipTime(inputDate);
//        把数据放入到excel中
//        1、创建一个工作薄 里面什么都没有
        Workbook workbook = new SXSSFWorkbook();

//        2、创建一个工作表 里面什么都没有
        Sheet sheet = workbook.createSheet("测试");

//        调整列宽
        sheet.setColumnWidth(1,26*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(2,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(3,26*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(4,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(5,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(6,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(7,16*256); //1代表一个字母宽度的256分之一
        sheet.setColumnWidth(8,16*256); //1代表一个字母宽度的256分之一

//        创建第一行的8个单元格
        Row row = sheet.createRow(0);
        row.setHeightInPoints(36);
        Cell cell = null;
        for (int i = 1; i <= 8; i++) {
            cell = row.createCell(i);
            cell.setCellStyle(bigTitle(workbook));
        }
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
//        2020-06---->2020年6月份出货表     2019-12--->2019年12月份出货表
        sheet.getRow(0).getCell(1).
                setCellValue(inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表");
//        第二行都是小标题
//        客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
        String title[] = new String[]{"客户","合同号","货号","数量","工厂","工厂交期","船期","贸易条款"};
        row = sheet.createRow(1);
        row.setHeightInPoints(26);
        for (int i = 1; i <= 8; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i-1]);
            cell.setCellStyle(title(workbook));
        }

//        导出具体的内容
        int rowIndex=2;
        for (ContractProductVo contractProductVo : contractProductVoList) {

            for (int i = 0; i < 6000; i++) {
            row = sheet.createRow(rowIndex);
//            客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
            row.setHeightInPoints(36);

            cell = row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName()); //客户
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo()); //合同号
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo()); //货号
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());//数量
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());//工厂
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(6);
            cell.setCellValue(sdf.format(contractProductVo.getDeliveryPeriod()));//工厂交期
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(7);
            cell.setCellValue(sdf.format(contractProductVo.getShipTime()));//船期
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());//贸易条款
//            cell.setCellStyle(text(workbook));
            rowIndex++;
            }
        }
//        文件导出 文件下载 一个流：文件的输出流  两个头：文件的打开方式、文件的mime类型
//        ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream); //把workbook中的内容写入到缓存流中
        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");

    }


    @RequestMapping(value = "/printExcelEasyPOI",name = "使用easyPOI导出excel")
    public void printExcelEasyPOI(String inputDate) throws Exception{
        String title = inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表";
        ExportParams exportParams = new ExportParams(title, "出货表");
        exportParams.setType(ExcelType.XSSF);
        List<ContractProductVo> list = contractService.findContractProductVoByShipTime(inputDate);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ContractProductVo.class, list);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream); //把workbook中的内容写入到缓存流中
        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");
    }



    @RequestMapping(value = "/submit",name = "提交购销合同")
    public String submit(String id) throws Exception{
//        目标就是修改购销合同的状态 update biao set state=1 where id=?
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(1);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }




    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }
}
